<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 基础表格 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
                <!-- <el-select v-model="query.address" placeholder="地址" class="handle-select mr10">
                    <el-option key="1" label="广东省" value="广东省"></el-option>
                    <el-option key="2" label="湖南省" value="湖南省"></el-option>
                </el-select> -->
                <el-input v-model="query.name" placeholder="产品名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-circle-plus" @click="handleAdd">添加商品</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
                <el-table-column prop="name" label="产品名称"></el-table-column>
                <el-table-column label="销售价格" width="100">
                    <template slot-scope="scope">￥{{ scope.row.price }}</template>
                </el-table-column>
                <el-table-column label="进货价格" width="100">
                    <template slot-scope="scope">￥{{ scope.row.in_price }}</template>
                </el-table-column>
                <el-table-column prop="supplier" label="生产厂商" width="350"></el-table-column>
                <el-table-column prop="made_in" width="100" label="产地"></el-table-column>

                <el-table-column prop="updated_at" label="更新时间" width="200"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.currentPage"
                    :page-size="query.pageSize"
                    :page-count="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="产品名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>                
                <el-form-item label="进货价￥">
                    <el-input type="number" v-model="form.in_price"></el-input>
                </el-form-item>
                <el-form-item label="销售价￥">
                    <el-input type="number" v-model="form.price"></el-input>
                </el-form-item>
                <el-form-item label="规格">
                    <el-input v-model="form.spec"></el-input>
                </el-form-item>
                <el-form-item label="品牌">
                    <el-input v-model="form.brand"></el-input>
                </el-form-item>
                <el-form-item label="单位">
                    <el-input v-model="form.unit"></el-input>
                </el-form-item>
                <el-form-item label="生产厂商">
                    <el-input v-model="form.supplier"></el-input>
                </el-form-item>
                <el-form-item label="产地">
                    <el-input v-model="form.made_in"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加弹出框 -->
        <el-dialog title="添加产品" :visible.sync="addVisible" width="35%">
            <el-form ref="form" :model="form" label-width="90px">
                <steambarcodereader @decode="addBarcode" width="200px" height="200px"></steambarcodereader>
                <el-form-item label="产品条形码">
                    <el-input v-model="form.barcode" @keyup.native="addBarcodeKeyPress" > </el-input>
                    {{ validateBarcodeMessage }}
                </el-form-item>
                <el-form-item label="产品名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="进货价￥">
                    <el-input type="number" v-model="form.in_price"></el-input>
                </el-form-item>
                <el-form-item label="销售价￥">
                    <el-input type="number" v-model="form.price"></el-input>
                </el-form-item>
                <el-form-item label="规格">
                    <el-input v-model="form.spec"></el-input>
                </el-form-item>
                <el-form-item label="品牌">
                    <el-input v-model="form.brand"></el-input>
                </el-form-item>
                <el-form-item label="单位">
                    <el-input v-model="form.unit"></el-input>
                </el-form-item>
                <el-form-item label="生产厂商">
                    <el-input v-model="form.supplier"></el-input>
                </el-form-item>
                <el-form-item label="产地">
                    <el-input v-model="form.made_in"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
// import { fetchData } from '../../api/index';

import steambarcodereader from '@/components/common/steambarcodereader.vue';
export default {
    name: 'ProductTable',
    data() {
        return {
            query: {
                name: '',
                currentPage: 1,
                pageSize: 10
            },
            tableData: [],
            multipleSelection: [], //多选框数组
            delList: [], //批量删除
            editVisible: false,
            addVisible: false,
            validateBarcodeMessage: '',
            validateBarcodeState:false,
            pageTotal: 0,
            form: {
                barcode: ''
            },
            idx: -1, //当前分页页面的第几行数据
            id: -1 //
        };
    },
    components: {
        //引入外部组件，这里是定义
        steambarcodereader
    },
    created() {
        this.InitData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        InitData() {
            this.getData();
        },
        async getData() {
            let res = await this.$http.post('getProductByPager', this.query);
            this.tableData = res.data.data;
            this.pageTotal = res.data.pageTotal;
            // fetchData(this.query).then(res => {
            //     console.log(res);
            //     this.tableData = res.list;
            //     this.pageTotal = res.pageTotal || 50;
            // });
        },
        // 触发搜索按钮
        handleSearch() {
            //this.$set(this.query, 'pageIndex', 1);
            this.InitData();
        },
        // 删除操作
        handleDelete(index, row) {
            let ids = row.id;
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.saveDelete(ids);                    
                    // this.tableData.splice(index, 1);
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 删除方法封装
        async saveDelete(ids) {
            let res = await this.$http.post('deleteProduct', { ids: ids });
            if (res.data) {
                this.$message.success(`删除了${ids}`);
                this.InitData();
            } else {
                this.$message.error(`删除了${ids}`);
            }
        },
        // 批量删除
        delAllSelection() {
            const length = this.multipleSelection.length;
            let ids = '';
            //this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                ids += this.multipleSelection[i].id + ',';
            }
            ids = ids.substring(0, ids.length - 1);

            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    //执行删除
                    this.saveDelete(ids);
                })
                .catch(() => {});
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
        },
        cancelAdd(){
            this.editVisible = false;
            this.destroyed();
        },
        // 保存编辑
        async saveEdit() {
            this.editVisible = false;
            let res = await this.$http.post('editProduct', this.form);
            if (res.data) {
                this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                this.InitData();
            } else {
                this.$message.error(`修改第 ${this.idx + 1} 行失败`);
            }

            //console.log(this.form);
            //this.$set(this.tableData, this.idx, this.form);
        },
        //添加操作
        handleAdd() {
            this.form ={};
            this.addVisible = true;
        },
        //保存添加
        async saveAdd() {
            this.addVisible = false;
            if(this.validateBarcodeState==false){
                this.$message.error('该二维码产品已经存在');
                return;
            }
            let res = await this.$http.post('addProduct', this.form);
            if (res.data) {
                this.$message.success('成功添加商品');
                this.InitData();                
            } else {
                this.$message.error('商品添加失败');
            }
            this.destroyed();
        },
        // 分页导航
        handlePageChange(val) {
            // console.log(val);
            // this.$set(this.query, 'currentPage', val);
            this.query.currentPage = val;
            this.getData();
        },
        //扫码添加商品
        addBarcode(barcode) {
            this.form.barcode = barcode;
            //强制vue组件重新渲染
            this.$forceUpdate();
            // this.$set(this.form,'barcode',barcode);
            this.validateBarcode();
        },
        addBarcodeKeyPress() {
            this.validateBarcode();
        },
        async validateBarcode() {
            if (this.form.barcode.length == 13) {
                //执行post操作
                let res = await this.$http.post('validateProductIsExist', this.form);
                if (res.data) {
                    this.validateBarcodeMessage = '条形码已经存在不可用';
                    this.validateBarcodeState = false;
                } else {
                    this.validateBarcodeMessage = '条形码可以使用';
                    this.validateBarcodeState = true;
                }
            }else{
                this.validateBarcodeMessage = '条形码长度不符合规范';
                this.validateBarcodeState = false;
            }
        },
        //关闭摄像头
        destroyed(){
          if(!this.mediaStreamTrack){
            return
          }
          this.mediaStreamTrack.srcObject.getTracks()[0].stop();
          this.trackerTask.stop();
          this.localVideoTrack.setMuted(true);
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
